package com.yugu.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.yugu.park.exception.BizException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Iterator;
import java.util.Map;

/**
 * @author guxf
 * @date 2021/11/23
 */
@Slf4j
public class DecryptUtils {


    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String getURL(String requestUrl, Map<String, String> map) {
        try {
            String param = "";
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                param += key + "=" + map.get(key) + "&";
            }
            return requestUrl + "?" + param;

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException();
        }
    }


    public static String decrypt(String data, String key, String iv, String encodingFormat) {
        try {
            //被加密的数据
            byte[] dataByte = Base64.decodeBase64(data);
            //加密秘钥
            byte[] keyByte = Base64.decodeBase64(key);
            //偏移量
            byte[] ivByte = Base64.decodeBase64(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                return new String(resultByte, encodingFormat);
            }
            return null;
        } catch (Exception e) {
            throw new BizException("encryptedData数据AES解密异常");
        }
    }

}
